<template>
  <Modal v-model="modalVisible" title="容器日志" @on-cancel="modalManiCancel" :width="1000">
    <div class="modal-log">
      <Button type="primary" @click="logClear">清屏</Button>
      <div class="log-body">
        <div v-html="modalForm.logs"></div>
      </div>
    </div>
    <div slot="footer">
      <Button type="warning" @click="modalManiCancel">取消</Button>
      <Button type="primary" :loading="isLoading" @click="modalManiConf">确定</Button>
    </div>
  </Modal>
</template>
<script type="text/javascript">

export default {
  data() {
    return {
      modalForm: {
        logs: ''
      },
      isLoading: false,
      modalRules: {
      },
      modalVisible: false,
      ws: null
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default: function () {
        return {}
      }
    },
    wsUrl: {
      type: String,
      default: ''
    }
  },
  mounted() {
  },
  methods: {
    // 清屏
    logClear() {
      this.modalForm.logs = ''
    },
    // 初始化，启动websocket
    init() {
      this.ws = new WebSocket('ws://' + this.wsUrl)
      this.ws.onopen = this.wsOnopen
      this.ws.onmessage = this.wsOnmessage
      this.ws.onclose = this.wsOnclose
    },
    wsOnopen() {
      this.ws.send(this.$route.params.environmentId + ',' + this.modalForm.id + ',0')
    },
    wsOnmessage(evt) {
      this.modalForm.logs += evt.data
    },
    wsOnclose(event) {
      // eslint-disable-next-line no-trailing-spaces
      this.ws = null
    },
    // 确定操作
    modalManiConf() {
      this.$emit('update:visible', false)
    },
    // 取消操作
    modalManiCancel() {
      this.$emit('update:visible', false)
    }
  },
  watch: {
    visible(val) {
      this.modalVisible = val
      if (val) {
        this.modalForm = Object.assign({}, this.form)
        this.init()
      }
    }
  },
  beforeDestroy() {
    this.ws && this.ws.close()
  }
}
</script>
<style lang="scss" scoped>
.modal-log {
  min-height: 400px;
}
.log-body {
  padding: 8px;
  margin-top: 10px;
  background-color: #f5f5f5;
  border: 1px solid #eee;
  border-radius: 6px;
  height: 340px;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
